<template>
 <div class="users">
   <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
   <!-- 搜索框 -->
      <el-input placeholder="请输入搜索内容" v-model="query" class="input-with-select">
        <el-button  @click= "searchUser"  slot="append" icon="el-icon-search"></el-button>
      </el-input>
      <el-button type = 'success' plain @click='showAdd'>添加用户</el-button>
   <!-- 表格 -->
        <el-table :data="userList">
          <el-table-column label="姓名" prop='username' ></el-table-column>
          <el-table-column label="邮箱" prop='email' ></el-table-column>
          <el-table-column label="电话" prop='mobilsize=small e' ></el-table-column>
          <el-table-column label="用户状态">
            <template v-slot:default='obj'>
              <el-switch
              @change='changeStarte(obj.row.id,obj.row.mg_state)'
              v-model="obj.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
            <!-- {{ obj.row.mg_state }} -->
            </template>
          </el-table-column>
          <el-table-column  label="操作">
            <template v-slot:default='{row}'>
               <el-button @click='showeditdialog(row)' size=mini plain  type="primary" icon='el-icon-edit'></el-button>
            <el-button @click="delUser(row.id)" size=mini  plain type="denger" icon='el-icon-delete'></el-button>
            <el-button @click='showassigndialog(row)' size=mini  plain type="success" icon='el-icon-check'>分配角色</el-button>
            </template>
          </el-table-column>
        </el-table>
      <!-- 分页 -->
    <el-pagination
        background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[1, 2, 4, 6]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

      <!-- 添加表单对话框 -->
      <el-dialog
       @close='closeDialog'
        title="添加用户"
        :visible.sync="dialogVisible"
        width="40%">

         <el-form ref='form' :rules="rules" :model='form' label-width="80px">
           <el-form-item label='用户名' prop ='username'>
             <el-input v-model='form.username' placeholder="请输入用户名"></el-input>
           </el-form-item>
           <el-form-item label='密码' prop ='password'>
             <el-input v-model='form.password' placeholder="请输入密码" type='password'></el-input>
           </el-form-item>
           <el-form-item label='邮箱' prop='email'>
             <el-input v-model='form.email' placeholder="请输入邮箱"></el-input>
           </el-form-item>
           <el-form-item label='手机号' prop='mobile'>
             <el-input v-model='form.mobile' placeholder="请输入手机号"></el-input>
           </el-form-item>
         </el-form>

        <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button @click='addUser' type="primary" >确 定</el-button>
        </span>
        </template>
      </el-dialog>

       <!-- 修改表单对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editVisible"
        width="40%">

         <el-form ref='editform' :rules="rules" :model='editform' label-width="80px">
           <el-form-item label='用户名' >
             <el-tag type='info'>{{ editform.username }}</el-tag>
           </el-form-item>
           <el-form-item label='邮箱' prop='email'>
             <el-input v-model='editform.email' placeholder="请输入邮箱"></el-input>
           </el-form-item>
           <el-form-item label='手机号' prop='mobile'>
             <el-input v-model='editform.mobile' placeholder="请输入手机号"></el-input>
           </el-form-item>
         </el-form>

        <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button @click='edituser' type="primary" >确 定</el-button>
        </span>
        </template>
      </el-dialog>

      <!-- 分配角色 -->
      <el-dialog
        title="分配角色"
        :visible.sync="assignVisible"
        width="40%">

         <el-form  :model='assignform' label-width="80px">
           <el-form-item label='用户名' >
             <el-tag type='info'>{{ assignform.username }}</el-tag>
           </el-form-item>

           <el-form-item label='角色列表'>
     <el-select v-model="assignform.rid" placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>
           </el-form-item>
         </el-form>

        <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="assignVisible = false">取 消</el-button>
          <el-button @click='assignrow' type="primary" >确 定</el-button>
        </span>
        </template>
      </el-dialog>
 </div>
</template>

<script>

export default {
  data () {
    return {
      inputValue: '',
      query: '',
      pagenum: 1,
      pagesize: 2,
      userList: [],
      total: 0,
      dialogVisible: false,
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: ['blur', 'change'] },
          { min: 3, max: 5, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入活动名称', trigger: ['blur', 'change'] },
          { min: 3, max: 5, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机', trigger: ['blur', 'change'] }
        ]
      },
      editVisible: false,
      editform: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      assignVisible: false,
      assignform: {
        username: '',
        id: '',
        rid: ''
      },
      options: []
    }
  },
  created () {
    // 进页面就渲染
    this.getUsersList()
  },
  methods: {
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.pagenum = 1
    },
    // 分页
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.pagenum = val
      // 重新渲染
      this.getUsersList()
    },
    // 封装后台请求
    async getUsersList () {
      const res = await this.$axios.get('users', {
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })
      const { data, meta } = res
      if (meta.status === 200) {
        this.userList = data.users
        this.total = data.total
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 搜索按钮
    searchUser () {
      this.pagenum = 1
      this.getUsersList()
    },
    // 修改按钮状态
    async changeStarte (id, type) {
      const { meta } = await this.$axios.put(`users/${id}/state/${type}`).then(res => {
        // console.log(res)
        // const { meta } = res
        if (meta.status === 200) {
          this.$message.success(meta.msg)
        } else {
          this.$message.error(meta.msg)
        }
      })
    },
    // 删除功能
    async delUser (id) {
      try {
        await this.$confirm('确认删除吗？', '温馨提示', {
          type: 'warning'
        })
        const { meta } = await this.$axios.delete(`users/${id}`)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          if (this.userList.length === 1 && this.pagenum > 1) {
            this.pagenum = 1
          }
          this.getUsersList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    showAdd () {
      this.dialogVisible = true
    },
    // 表单检验
    async addUser () {
      try {
        await this.$refs.form.validate()
        // 发送请求
        const { meta } = await this.$axios.post('users', this.form)
        // console.log(res)
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          // 关闭对话框
          this.dialogVisible = false
          // 重新渲染最后一页
          this.pagenum = Math.ceil(++this.total / this.pagesize)
          this.getUsersList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 重置表单
    closeDialog () {
      this.$refs.form.resetFields() // 确定关闭重置表单
    },
    // 修改
    showeditdialog (row) {
      // 点击修改原有数据显示出来
      this.editVisible = true
      this.editform.id = row.id
      this.editform.username = row.username
      this.editform.email = row.email
      this.editform.mobile = row.mobile
    },
    async edituser () {
      try {
        // 先校验
        await this.$refs.editform.validate()
        // 发送请求
        const { id, email, mobile } = this.editform
        const { meta } = await this.$axios.put(`users/${id}`, { email, mobile })
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          // 关闭对话框
          this.editVisible = false
          // 重新渲染
          this.getUsersList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    async showassigndialog (row) {
      // 回显之前的角色
      this.assignVisible = true
      this.assignform.id = row.id
      this.assignform.username = row.username
      // this.assignform.rid=row,发请求拿角色id
      const resuser = await this.$axios.get(`users/${row.id}`)
      if (resuser.meta.status === 200) {
        // 新用户rid是-1，给‘’
        const rid = resuser.data.rid
        this.assignform.rid = rid === -1 ? '' : rid
      }

      // 发请求
      const { data, meta } = await this.$axios.get('roles')
      if (meta.status === 200) {
        this.options = data
      } else {
        this.$message.error(meta.msg)
      }
    },
    async assignrow () {
      const { id, rid } = this.assignform
      if (rid === '') {
        this.$message.error('请选择角色')
        return
      }
      const { meta } = await this.$axios.put(`users/${id}/role`, { rid })
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        this.assignVisible = false
        this.getUsersList()
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}

</script>

<style lang = 'less' scoped>
.users{

   .input-with-select{
     width: 300px;
     margin-bottom: 10px;
     margin-right: 10px;
   }

}

</style>
